package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.data.bean.response.UserInfoResponse
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.PackageUtils
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.data.bean.response.TaskListResponse
import com.lykj.llw.box.databinding.ActAwardTaskBinding
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import retrofit2.Retrofit

/**
 * ================================================
 * 有奖任务页面
 * ================================================
 *
 * @author gosha
 * @date 2023/10/16-17:40
 */
class AwardTaskActivity : BaseActivity() {
    lateinit var binding: ActAwardTaskBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActAwardTaskBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        obtainIntegralInfo()
        obtainTaskInfo()
    }

    override fun initUI() {
        FlowBus.with<String>("updatePtb").register(this) {
            finish()
        }
    }

    //获取奖励任务信息
    private fun obtainTaskInfo() {
        RetrofitManager.instance.obtainAwardTaskList(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@AwardTaskActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, TaskListResponse::class.java)

                if (!bean.data.taskList.isNullOrEmpty()) {
                    //设置任务列表完成状态
                    bean.data.taskList.forEach {
                        when (it.id) {
                            1 -> {
                                when (it.status) {
                                    -1 -> {
                                        binding.tvOpenVipCard.text = "去开通"
                                    }

                                    0 -> {
                                        binding.tvOpenVipCard.text = "领取"
                                    }

                                    1 -> {
                                        binding.tvOpenVipCard.text = "已领取"
                                    }
                                }
                            }

                            2 -> {
                                if (it.status == -1) {
                                    binding.tvSignIn.text = "签到"
                                } else if (it.status == 1) {
                                    binding.tvSignIn.text = "已签到"
                                }
                            }

                            3 -> {
                                when (it.status) {
                                    -1 -> {
                                        binding.tvVerfity.text = "去实名"
                                    }

                                    0 -> {
                                        binding.tvVerfity.text = "领取"
                                    }

                                    1 -> {
                                        binding.tvVerfity.text = "已领取"
                                    }
                                }
                            }

                            4 -> {
                                when (it.status) {
                                    -1 -> {
                                        binding.tvBindPhone.text = "去绑定"
                                    }

                                    0 -> {
                                        binding.tvBindPhone.text = "领取"
                                    }

                                    1 -> {
                                        binding.tvBindPhone.text = "已领取"
                                    }
                                }
                            }

                            9 -> {
                                when (it.status) {
                                    -1 -> {
                                        binding.tvBindWx.text = "去认证"
                                    }

                                    0 -> {
                                        binding.tvBindWx.text = "领取"
                                    }

                                    1 -> {
                                        binding.tvBindWx.text = "已领取"
                                    }
                                }
                            }
                        }
                    }
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@AwardTaskActivity, it)
                }
            }
        })
    }

    //领取任务奖励
    private fun receiverTaskAward(taskId: String) {
        RetrofitManager.instance.receiverAwardTask(taskId,
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@AwardTaskActivity, d)
                }

                override fun specificHandle(responseBody: String) {
                    var msg = "签到成功"

                    when (taskId) {
                        //开通会员
                        "1" -> {
                            msg = "开通会员成功,积分+500"
                        }
                        //签到
                        "2" -> {
                            msg = "签到成功,积分+10"
                        }
                        //实名认证
                        "3" -> {
                            msg = "实名认证成功,积分+50"
                        }
                        //绑定手机
                        "4" -> {
                            msg = "绑定手机成功,积分+50"
                        }

                        "9" -> {
                            msg = "微信号认证成功,积分+5"
                        }
                    }

                    obtainIntegralInfo()
                    obtainTaskInfo()

                    ToastUtils.showShort(this@AwardTaskActivity, msg)
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(this@AwardTaskActivity, it)
                    }
                }
            })
    }

    //获取用户积分信息
    private fun obtainIntegralInfo() {
        RetrofitManager.instance.obtainUserInfo(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, UserInfoResponse::class.java)

                binding.tvMyIntegral.text = "我的积分：${bean.data?.integral}"
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { LogUtils.e("$msg") }
            }
        })
    }

    //微信认证
    private fun bindWx(taskId: String) {
        RetrofitManager.instance.bindWx(taskId,
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@AwardTaskActivity, d)
                }

                override fun specificHandle(responseBody: String) {
                    Log.e("Task", "微信认证成功")
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(this@AwardTaskActivity, it)
                    }
                }
            })
    }

    override fun initData() {
    }

    override fun setListener() {
        binding.ivBack.clickWithTrigger {
            finish()
        }

        binding.tvBtnExchange.clickWithTrigger {
            startActivity(Intent(this, IntegralExchangeActivity::class.java))
        }

        binding.tvSignIn.clickWithTrigger {
            if (binding.tvSignIn.text.equals("已签到")) {
                ToastUtils.showShort(this, "已签到,无需再次签到")
                return@clickWithTrigger
            }

            receiverTaskAward("2")
        }

        binding.tvOpenVipCard.clickWithTrigger {
            when (binding.tvOpenVipCard.text) {
                "去开通" -> {
                    finish()

                    FlowBus.with<Int>(BConstants.BUS_KEY.HOME_SWITCH_NAV).post(lifecycleScope, 1)
                }

                "领取" -> {
                    receiverTaskAward("1")
                }

                "已领取" -> {
                    ToastUtils.showShort(this, "已领取奖励,请勿多次领取")
                }
            }
        }

        binding.tvVerfity.clickWithTrigger {
            when (binding.tvVerfity.text) {
                "去实名" -> {
                    startActivity(Intent(this, RealNameAuthActivity::class.java))
                }

                "领取" -> {
                    receiverTaskAward("3")
                }

                "已领取" -> {
                    ToastUtils.showShort(this, "已领取奖励,请勿多次领取")
                }
            }
        }

        binding.tvBindPhone.clickWithTrigger {
            when (binding.tvBindPhone.text) {
                "领取" -> {
                    receiverTaskAward("4")
                }

                "已领取" -> {
                    ToastUtils.showShort(this, "已领取奖励,请勿多次领取")
                }
            }
        }

        binding.tvBindWx.clickWithTrigger {
            when (binding.tvBindWx.text) {
                "去认证" -> {
                    val pName = "com.tencent.mm"
                    if (PackageUtils.checkApk(this, pName)) {
                        try {
                            val intent =
                                packageManager.getLaunchIntentForPackage(pName)
                            startActivity(intent)
                        } catch (e: Exception) {
                        }

                        bindWx("9")
                    } else {
                        ToastUtils.showShort(this@AwardTaskActivity, "微信未安装")
                    }
                }

                "领取" -> {
                    receiverTaskAward("9")
                }

                "已领取" -> {
                    ToastUtils.showShort(this, "已领取奖励,请勿多次领取")
                }
            }
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}